package it.alertManager.rss;

import it.alertManager.exceptions.AlertManagerException;
import it.alertManager.horoscope.HTTPHoroscopeReader;
import it.alertManager.util.CommonData;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.content.res.Resources;
import android.speech.tts.TextToSpeech;
import android.util.Log;

public class HTTPRSSReader {
	
	private static final String LOG_CLASS_NAME = HTTPHoroscopeReader.class.getName();
	
	public void readRSSFromURL(Resources res, TextToSpeech textToSpeech, String rssURL, boolean onlyTitle, int numOfItem) throws AlertManagerException
	{
		Log.d(LOG_CLASS_NAME,"Enter readRSSFromURL ");	

		rssURL = "http://www.corriere.it/rss/cinema.xml";

		String responseBody = null;
		try {
			Log.d(LOG_CLASS_NAME,"Connetting to " + rssURL);	
			responseBody = CommonData.getResponse(rssURL);
			
			DocumentBuilder builderRSSURL = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builderRSSURL.parse(new InputSource(new StringReader(responseBody)));
			NodeList languageNL = doc.getElementsByTagName("language");
			String language = languageNL.item(0).getFirstChild().getNodeValue();
			language = language.substring(0, language.indexOf('-'));
			
			textToSpeech.setLanguage(CommonData.getLanguage(language, Locale.ENGLISH));
			textToSpeech.setSpeechRate(CommonData.SPEACH_RATE);
			
			Log.d(LOG_CLASS_NAME, "language = " + language);
			
			// Retrieving title information
			ArrayList<String> titleArrayList = new ArrayList<String>();
			NodeList itemNL = doc.getElementsByTagName("title");

			// Calculating the number of item to read +2 to remove the head of rss
			int finalNumOfItemToRead = itemNL.getLength();
			if (numOfItem != CommonData.ALL_RSS_ITEM && numOfItem <=finalNumOfItemToRead)
				finalNumOfItemToRead = numOfItem+2;

			for (int ij=0; ij < finalNumOfItemToRead; ij++)
			{
				Node itemTitle = itemNL.item(ij);
				if ("item".equals(itemTitle.getParentNode().getNodeName()))
				{	
					String titleItem = itemTitle.getFirstChild().getNodeValue();
					if (titleItem != null && !"".equals(titleItem.trim()))
						titleItem = titleItem + (titleItem.endsWith(".") ? "" : ".");
					titleArrayList.add(titleItem);
					Log.d(LOG_CLASS_NAME, "titleItem = " + titleItem);

					// Immediate reading for only title
					if (onlyTitle)
						textToSpeech.speak(titleItem, TextToSpeech.QUEUE_ADD, null);
				}
			}

			// Retrieving description information
			ArrayList<String> descArrayList = new ArrayList<String>();
			if (onlyTitle == false)
			{
				NodeList descNL = doc.getElementsByTagName("description");
				for (int ij=0; ij < finalNumOfItemToRead; ij++)
				{
					Node itemDesc = descNL.item(ij);
					if ("item".equals(itemDesc.getParentNode().getNodeName()))
					{	
						String descItem = new String(itemDesc.getFirstChild().getNodeValue().getBytes(), "UTF-8");
						if (descItem != null && !"".equals(descItem.trim()))
							descItem = new String((descItem + (descItem.endsWith(".") ? "" : ".")).getBytes("UTF-8"));
						descArrayList.add(descItem);
						Log.d(LOG_CLASS_NAME, "descItem = " + descItem);
						
						// Read title and description
						HashMap t2sHashMap = new HashMap();
						t2sHashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,0xDEADBEEF);
						textToSpeech.speak(titleArrayList.get(ij-2) + " " + CommonData.vowelsTransformation(descArrayList.get(ij-2)), TextToSpeech.QUEUE_ADD, t2sHashMap);						
					}
				}
				Log.d(LOG_CLASS_NAME, "FINAL #title:" + titleArrayList.size() + " #desc:" + descArrayList.size());
			}
			
		} catch (ClientProtocolException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPRSSReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPRSSReader: " + e.getMessage(), e);
		} catch (IOException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPRSSReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPRSSReader: " + e.getMessage(), e);
		} catch (ParserConfigurationException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPRSSReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPRSSReader: " + e.getMessage(), e);
		} catch (FactoryConfigurationError e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPRSSReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPRSSReader: " + e.getMessage(), e);
		} catch (SAXException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPRSSReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPRSSReader: " + e.getMessage(), e);
		}
		finally
		{
			Log.d(LOG_CLASS_NAME,"Exit readRSSFromURL ");		
		}		
	}	
}
